<?php 
class Terminal 
{
	public $AutoAuth;
	public $PaymentMethodList;
	public $Language;
	public $OrderDescription;
	public $RedirectOnError;
	public $RedirectUrl;
	
	function Terminal($AutoAuth, $PaymentMethodList, $Language, $OrderDescription, $RedirectOnError, $RedirectUrl)
	{
		$this->AutoAuth           = $AutoAuth;
		$this->PaymentMethodList  = $PaymentMethodList;
		$this->Language           = $Language;
		$this->OrderDescription   = $OrderDescription;
		$this->RedirectOnError    = $RedirectOnError;
		$this->RedirectUrl        = $RedirectUrl;
	}
};

class QueryRequest 
{
	public $TransactionId;
	function QueryRequest($TransactionId)
	{
		$this->TransactionId = $TransactionId;
	}
};

class ProcessRequest 
{
  
	public $Description;
	public $Operation;
	public $TransactionAmount;
	public $TransactionId;
	public $TransactionReconRef;
	
	function ProcessRequest($Description, $Operation, $TransactionAmount, $TransactionId, $TransactionReconRef)
	{
		$this->Description          = $Description;
		$this->Operation            = $Operation;
		$this->TransactionAmount    = $TransactionAmount;
		$this->TransactionId        = $TransactionId;
		$this->TransactionReconRef  = $TransactionReconRef;
	}
};

class PaymentNETS extends Object
{
	public $Terminal;
	public $TerminalURL;
	public $TerminalParams;
	
	public $MerchantId;
	public $MerchantUname;
	public $MerchantPass;
	
	public $Language;
	public $TestMode;
	public $Amount;
	public $CurrencyCode;
	public $CurrencyNum;
	public $OrderId;
	public $Status;
	
	public $ComId;
	public $AcceptURL;
	public $CallbackURL;
	public $CancelURL;

	public $Transact;
	public $Parameters;
	public $Request;
	public $Order;
	public $Customer;
	
	public $RegisterRequest;
	public $ProcessRequest;
	public $Enviroment;
	
	public function PaymentNETS() 
	{ 
		global $katana;
		
		$this->AcceptURL = SITE_URL.'?c='.$katana->getComID().'&action=payment_accept';
		$this->CallbackURL = SITE_URL.'plugins/payment/nets_callback.php';
	    $this->CancelURL = SITE_URL.'plugins/payment/nets_cancel.php';
		$this->ComId = 16;
		
		$this->Enviroment['Language']  			= null;
		$this->Enviroment['OS']  				= null;
		$this->Enviroment['WebServicePlatform']	= 'PHP5';
		
		$this->TerminalURL	= 'https://epayment.bbs.no/terminal/default.aspx';
		self::loadConfig(); 
	}
	
	private function loadConfig()
	{
		$select  = 'SELECT site_id, param, value FROM '.DB_PERFIX.'shop_payment_config ';
		$select .= 'WHERE payment_id=6 AND (site_id='.SITE_ID.' OR site_id=0);';
		$result = mysql_query($select);
		if(mysql_num_rows($result) > 0)
		{
			while($row = mysql_fetch_array($result))
			{ $config[$row['site_id']][$row['param']] = $row['value']; }
			if($config[SITE_ID])
			{ $c = SITE_ID; }
			else
			{ $c = 0; }
			
			self::setMerchantId($config[$c]['merchantId']);
			self::setTestMode($config[$c]['testMode']);
			self::setMerchantPass($config[$c]['token']);
			self::setCurrencyCode($config[$c]['currencyCode']);
			self::setLanguage($config[$c]['language']);
			
			$this->Parameters['merchantId'] = self::getMerchantId();
			$this->Parameters['token'] 		= self::getMerchantPass();
		}
	}
	
	public function prepareOrder($order)
	{
		if($order)
		{
			if($order->getId() > 0)
			{
				global $txt;
				
				$wsdl = "https://epayment.bbs.no/netaxept.svc?wsdl";
				$terminal = "https://epayment.bbs.no/terminal/default.aspx";
				$TransactionId = '';
				
				$this->Customer['Address1'] = $txt->formatText($order->getDeliveryAddress());
                $this->Customer['Address2'] = $txt->formatText($order->getDeliveryAddress2());
                $this->Customer['CompanyName'] = '';
                $this->Customer['CompanyRegistrationNumber'] = '';
                $this->Customer['Country'] = 'NO';
                $this->Customer['CustomerNumber'] = '';
                $this->Customer['Email'] = '';
                $this->Customer['FirstName'] = $txt->formatText($order->getDeliveryName());
                $this->Customer['LastName'] = $txt->formatText($order->getDeliveryLastName());
                $this->Customer['PhoneNumber'] = '';
                $this->Customer['Postcode'] = $order->getDeliveryZip(4);
                $this->Customer['SocialSecurityNumber'] = '';
                $this->Customer['Town'] = $txt->formatText($order->getDeliveryCity());
				
				$this->Order['OrderNumber']  = $order->getId();
				$this->Order['Amount'] 		 = number_format(($order->getCostTotal(1)*100),0,'','');
				$this->Order['CurrencyCode'] = self::getCurrencyCode();
				
				$this->Terminal = new Terminal($autoAuth, $paymentMethodList, self::getLanguage(), $order->getDeliveryComment(), $redirectOnError, $this->AcceptURL.'&orderid='.$order->getId());
				
				//$this->Terminal['Language'] 		= self::getLanguage();
				//$this->Terminal['RedirectUrl'] 		= $this->AcceptURL.'&orderid='.$order->getId();
				//$this->Terminal['OrderDescription'] = $order->getDeliveryComment();

				$paymentform .= '<input type="hidden" name="priceinfo1.shippingcosts" value="'.number_format(($order->getCostShipping()*100),0,'','').'" />';
				$paymentform .= '<input type="hidden" name="priceinfo2.VAT" value="'.number_format(($order->getCostItemsVat()*100),0,'','').'" />';

				$this->RegisterRequest['Customer']  = $this->Customer;
				$this->RegisterRequest['Order'] 	= $this->Order;
				$this->RegisterRequest['Terminal']  = $this->Terminal;
				$this->RegisterRequest['AvtaleGiro']           = null; // Optional parameter
				$this->RegisterRequest['CardInfo']             = null; // Optional parameter
				$this->RegisterRequest['description']          = "description of Order Registration"; // Optional parameter
				$this->RegisterRequest['DnBNorDirectPayment']  = null; // Optional parameter
				$this->RegisterRequest['Environment']          = $this->Enviroment;
				$this->RegisterRequest['MicroPayment']         = null; // Optional parameter
				$this->RegisterRequest['serviceType']          = null; // Optional parameter
				$this->RegisterRequest['Recurring']            = null; // Optional parameter
				$this->RegisterRequest['transactionId']        = null; // Optional parameter
				$this->RegisterRequest['transactionReconRef']  = null; // Optional parameter

				$InputParametersOfRegister = array
				(
					"token"                 => self::getMerchantPass(),
					"merchantId"            => self::getMerchantId(),
					"request"               => $this->RegisterRequest
				);
				/*
				echo "<br/>Parameters in RegisterRequest<br/>"; 
				echo "<pre>"; 
				echo print_r($InputParametersOfRegister); 
				echo "</pre>";
				*/
				try 
				{
					if (strpos($_SERVER["HTTP_HOST"], 'uapp') > 0)
					{
						// Creating new client having proxy
						$client = new SoapClient($wsdl, array('proxy_host' => "isa4", 'proxy_port' => 8080, 'trace' => true,'exceptions' => true));
					}
					else
					{
						// Creating new client without proxy
						$client = new SoapClient($wsdl, array('trace' => true,'exceptions' => true ));
					}
				
					$OutputParametersOfRegister = $client->__call('Register', array("parameters"=>$InputParametersOfRegister));
					
					// RegisterResult
					$RegisterResult = $OutputParametersOfRegister->RegisterResult; 
					
					$this->TerminalParams = "?merchantId=".$this->Parameters['merchantId']."&transactionId=".$RegisterResult->TransactionId;
					
					$terminal_parameters = "?merchantId=". $this->Parameters['merchantId'] . "&transactionId=" .  $RegisterResult->TransactionId;  
					$process_parameters = "?transactionId=" .  $RegisterResult->TransactionId;  
					
					$TransactionId = $RegisterResult->TransactionId;
					
					$order->setPaymentTransact($RegisterResult->TransactionId);
					$order->updateOrder();
					/*
					echo "<h3><font color='gray'>Output parameters:</font></h3>";
					
					echo "TransactionId= " . $RegisterResult->TransactionId . "<br/>";

					// you can also display this way
					echo "<br/>Parameters in RegisterResult<br/>"; 
					echo "<pre>"; 
					echo print_r($RegisterResult); 
					echo "</pre>";
					*/
					/*
					echo "<h3><font color='green'>Register call successfully done.</font></h3>";
					
					echo "<h3><a href='$terminal$terminal_parameters'>Go to Netaxept Terminal 2.0</a></h3>";
					
					echo "<h3><a href='callingQuery.php$process_parameters'>Calling Query</a></h3>";
					*/
				}
				catch (SoapFault $fault) 
				{
					// Printing errors from the communication
					echo "<h3><a href='index.php'>Test Webshops</a><h3>";
					echo "<h3><font color='red'>EXCEPTION IN REGISTER CALL:</font></h3>";
					echo "<pre>"; 
					print_r($fault);
					echo "</pre>";
				}
				
				
				return $TransactionId;
			}
		}
	}
	
	public function validateOrder($order)
	{
		if($order->getPaymentTransact())
		{
			$status = self::Authorize($order);
			if($status == 'OK')
			{
				//$order->setPaymentTransact($this->Transact);
				$order->setPaymentStatus(1);
				$order->updateOrder();
			}
			return $status;
		}
	}
	
	function Authorize($order) 
	{
		$wsdl = "https://epayment.bbs.no/netaxept.svc?wsdl";
		$terminal = "https://epayment.bbs.no/terminal/default.aspx";
		
		$transactionId = $order->getPaymentTransact();
		$description = "description of AUTH operation";
		$operation = "AUTH";
		$transactionAmount = ""; //number_format(($order->getCostTotal(1)*100),0,'','');
		$transactionReconRef = "";

		$this->ProcessRequest = new ProcessRequest(
		  $description,
		  $operation,
		  $transactionAmount,
		  $transactionId,
		  $transactionReconRef
		);
		
		$InputParametersOfProcess = array
		(
		  "token"       => self::getMerchantPass(),
		  "merchantId"  => self::getMerchantId(),
		  "request"     => $this->ProcessRequest
		);
	
		/*
		echo "<br/>Parameters in ProcessRequest<br/>"; 
		echo "<pre>"; 
		echo print_r($InputParametersOfProcess); 
		echo "</pre>";
		*/
		
		try 
		{
			if (strpos($_SERVER["HTTP_HOST"], 'uapp') > 0)
			{
				// Creating new client having proxy
				$client = new SoapClient($wsdl, array('proxy_host' => "isa4", 'proxy_port' => 8080, 'trace' => true,'exceptions' => true));
			}
			else
			{
				// Creating new client without proxy
				$client = new SoapClient($wsdl, array('trace' => true,'exceptions' => true ));
			}
				
			$OutputParametersOfProcess = $client->__call('Process' , array("parameters"=>$InputParametersOfProcess));
			
			$ProcessResult = $OutputParametersOfProcess->ProcessResult; 
			/*
			echo "<h3><font color='gray'>Output parameters:</font></h3>";
			echo "<pre>"; 
			print_r($ProcessResult);
			echo "</pre>";
			
			echo "<h3><font color='green'>Process call successfully done.</font></h3>";
			*/
			$process_parameters = "?transactionId=" .  $ProcessResult->TransactionId;
			
			if($ProcessResult->ResponseCode == "OK")
			{
				$out = $ProcessResult->ResponseCode;
				/*
				echo "<br/>ResponseCode is OK, so you can call Capture or Annul:";
				echo "<h3><a href='callingCapture.php$process_parameters'>Calling Capture</a></h3>";
				echo "<h3><a href='callingAnnul.php$process_parameters'>Calling Annul</a></h3>";
				echo "<h3><a href='callingQuery.php$process_parameters'>Calling Query</a></h3>";
				echo "<h3><a href='index.php'>Test Webshops</a><h3>";
				*/
			}
		} // End try
		catch (SoapFault $fault) 
		{
			## Do some error handling in here...
			/*
			echo "<h3><a href='index.php'>Test Webshops</a><h3>";
			
			echo "<br/><font color='red'>EXCEPTION!";   
			echo "<br/><br/><h3><font color='red'>Process call failed</font></h3>";
			echo "<pre>"; 
			*/
			if($fault->getMessage() == 'Transaction already processed')
			{
				$out = 'OK';
			}
			else
			{
			 	$out = $fault->getMessage();
			}
			//print_r($fault);
			//echo "</pre>";
		} // End catch
		  
		return $out;
	}
	
	function Capture($order) 
	{
		$wsdl = "https://epayment.bbs.no/netaxept.svc?wsdl";
		$terminal = "https://epayment.bbs.no/terminal/default.aspx";
		
		$transactionId = $order->getPaymentTransact();
		$description = "description of CAPTURE operation";
		$operation = "CAPTURE";
		$transactionAmount = ""; //number_format(($order->getCostTotal(1)*100),0,'','');
		$transactionReconRef = "";

		$this->ProcessRequest = new ProcessRequest(
		  $description,
		  $operation,
		  $transactionAmount,
		  $transactionId,
		  $transactionReconRef
		);
		
		$InputParametersOfProcess = array
		(
		  "token"       => self::getMerchantPass(),
		  "merchantId"  => self::getMerchantId(),
		  "request"     => $this->ProcessRequest
		);
	
		/*
		echo "<br/>Parameters in ProcessRequest<br/>"; 
		echo "<pre>"; 
		echo print_r($InputParametersOfProcess); 
		echo "</pre>";
		*/
		
		try 
		{
			if (strpos($_SERVER["HTTP_HOST"], 'uapp') > 0)
			{
				// Creating new client having proxy
				$client = new SoapClient($wsdl, array('proxy_host' => "isa4", 'proxy_port' => 8080, 'trace' => true,'exceptions' => true));
			}
			else
			{
				// Creating new client without proxy
				$client = new SoapClient($wsdl, array('trace' => true,'exceptions' => true ));
			}
				
			$OutputParametersOfProcess = $client->__call('Process' , array("parameters"=>$InputParametersOfProcess));
			
			$ProcessResult = $OutputParametersOfProcess->ProcessResult; 
			/*
			echo "<h3><font color='gray'>Output parameters:</font></h3>";
			echo "<pre>"; 
			print_r($ProcessResult);
			echo "</pre>";
			
			echo "<h3><font color='green'>Process call successfully done.</font></h3>";
			*/
			$process_parameters = "?transactionId=" .  $ProcessResult->TransactionId;
			
			if($ProcessResult->ResponseCode == "OK")
			{
				$out = $ProcessResult->ResponseCode;
				/*
				echo "<br/>ResponseCode is OK, so you can call Capture or Annul:";
				echo "<h3><a href='callingCapture.php$process_parameters'>Calling Capture</a></h3>";
				echo "<h3><a href='callingAnnul.php$process_parameters'>Calling Annul</a></h3>";
				echo "<h3><a href='callingQuery.php$process_parameters'>Calling Query</a></h3>";
				echo "<h3><a href='index.php'>Test Webshops</a><h3>";
				*/
			}
		} // End try
		catch (SoapFault $fault) 
		{
			## Do some error handling in here...
			/*
			echo "<h3><a href='index.php'>Test Webshops</a><h3>";
			
			echo "<br/><font color='red'>EXCEPTION!";   
			echo "<br/><br/><h3><font color='red'>Process call failed</font></h3>";
			echo "<pre>"; 
			*/
			if($fault->getMessage() == 'Transaction already processed')
			{
				$out = 'OK';
			}
			else
			{
			 	$out = $fault->getMessage();
			}
			//print_r($fault);
			//echo "</pre>";
		} // End catch
		  
		return $out;
	}
	
	function GetStatus($order) 
	{
		$wsdl = "https://epayment.bbs.no/netaxept.svc?wsdl";
		$terminal = "https://epayment.bbs.no/terminal/default.aspx";
		
		$QueryRequest = new QueryRequest($order->getPaymentTransact()); 
		
		$InputParametersOfQuery = array
		(
		  "token"       => self::getMerchantPass(),
		  "merchantId"  => self::getMerchantId(),
		  "request"     => $QueryRequest
		);
	
		/*
		echo "<br/>Parameters in ProcessRequest<br/>"; 
		echo "<pre>"; 
		echo print_r($InputParametersOfProcess); 
		echo "</pre>";
		*/
		
		try 
		{
			if (strpos($_SERVER["HTTP_HOST"], 'uapp') > 0)
			{
				// Creating new client having proxy
				$client = new SoapClient($wsdl, array('proxy_host' => "isa4", 'proxy_port' => 8080, 'trace' => true,'exceptions' => true));
			}
			else
			{
				// Creating new client without proxy
				$client = new SoapClient($wsdl, array('trace' => true,'exceptions' => true ));
			}
				
			$OutputParametersOfQuery = $client->__call('Query' , array("parameters"=>$InputParametersOfQuery));
			
			$QueryResult = $OutputParametersOfQuery->QueryResult;
			
			
			echo "<h3><font color='gray'>Output parameters:</font></h3>";
			echo "<pre>"; 
			print_r($ProcessResult);
			echo "</pre>";
			echo "<h3><font color='green'>Process call successfully done.</font></h3>";
			
			$out = $QueryResult;
		} // End try
		catch (SoapFault $fault) 
		{
			$out = $fault->getMessage();
		} // End catch
		  
		return $out;
	}
}
?>